﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _32
{
    class MI
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        public void doSomeWorkSync(object obj)
        {
            Console.WriteLine("doSomeWorkSync()" + "--Lock held by Thread:" + obj.ToString()+ "  HashCode=" + Thread.CurrentThread.GetHashCode());

            Thread.Sleep(5 * 1000);
            Console.WriteLine("doSomeWorkSync()" + "--Lock released by Thread:" + obj.ToString() + "  HashCode=" + Thread.CurrentThread.GetHashCode());
        }


        public void doSomeWorkNoSync(object obj)
        {
            Console.WriteLine("doSomeWorkNoSync()" + "--Entered released by Thread:" + obj.ToString() + "  HashCode=" + Thread.CurrentThread.GetHashCode());

            Thread.Sleep(5 * 1000);
            Console.WriteLine("doSomeWorkNoSync()" + "--Leaving released by Thread:" + obj.ToString() + "  HashCode=" + Thread.CurrentThread.GetHashCode());
        }
        [STAThread]
        static void Main(string[] args)
        {
            MI m = new MI();
            //Delegate for Non-sync operation
            ParameterizedThreadStart tsNoSyncDelegate = new ParameterizedThreadStart(m.doSomeWorkNoSync);

            ParameterizedThreadStart tsSyncDelegate = new ParameterizedThreadStart(m.doSomeWorkSync);

            Thread t1 = new Thread(tsNoSyncDelegate);
            Thread t2 = new Thread(tsNoSyncDelegate);

            t1.Start("t1");
            t2.Start("t2");

            Thread t3 = new Thread(tsSyncDelegate);
            Thread t4 = new Thread(tsSyncDelegate);
            t3.Start("t3");
            t4.Start("t4");

            Console.WriteLine("完成");
            Console.ReadLine();
        }
    }
}
